<?php

namespace app\common\model;

use app\common\library\Weixin;
use think\Db;
use think\Exception;
use think\Model;


class AgentShop extends Model
{

    

    

    // 表名
    protected $name = 'agent_shop';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
		'role_text',
	    'status_text',
	    'area_text'
    ];
    
    
    public function getRoleTextAttr($value, $data) {
    	$value = $value ?　: $data['role'];
    	$list = \app\admin\model\User::$levelList;
    	return $list[$value] ??'';
    }

    const STATUS_Y = 1;
    const STATUS_D = 0;
    
    public static $statusList = [
        self::STATUS_Y => '正常',
	    self::STATUS_D => "禁用"
    ];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ?　: $data['status'];
		$list = self::$statusList;
		return $list[$value] ??'';
	}
	
	public function getAreaTextAttr($value, $data) {
		$value = $value ? : $data['area'];
		$list = \app\admin\model\User::$areaList;
		return $list[$value] ??'';
	}
	
	
	
    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['sort' => $row[$pk]]);
        });
    }
    
    public function user() {
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	public function recommend() {
		return $this->belongsTo('user', 'recommend_user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function warehouse() {
		return $this->belongsTo('agentShop', 'warehouse_id', 'id', '', 'left')->setEagerlyType(0);
	}
	public function center() {
		return $this->belongsTo('agentShop', 'center_id', 'id', '', 'left')->setEagerlyType(0);
	}
	public function theater() {
		return $this->belongsTo('agentShop', 'theater_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 根据用户ID获取代理信息
	 * @param $userId
	 * @return array|false|\PDOStatement|string|Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getInfoByUserId($userId) {
		$agentInfo = Db::name('agentShop')
			->where(['user_id' => $userId])
			->find();
		
		return $agentInfo;
	}
	
	/**
	 * 添加销量
	 * @param $id
	 * @param $number
	 * @param $amount
	 * @return int|string
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function addNumber($id, $number, $amount, $orderNumber = 1, $orderId, $agentId = '', $promotionId = '') {
    	$shop = $this->find($id);
		
		$itemRes = SaleItem::addRow($orderId, $shop['user_id'], $number, $agentId, $promotionId);
		if(!$itemRes) {
			$this->error = '添加代理销量记录出错';
			return false;
		}
		
    	return Db::name('agentShop')
		    ->where(['id' => $id])
		    ->update([
		    	'sale_number' => $shop['sale_number'] + $number,
			    'order_number' => $shop['order_number'] + $orderNumber,
			    'sale_amount' => $shop['sale_amount'] + $amount
		    ]);
	}
	
	
	/**
	 * 发送用户下单提醒库存模板
	 * @param $userId
	 * @param $name
	 * @return string
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function sendOrderTemplate($userId, $name) {
		$config = config('weixin');
		$appid = $config['smallapp']['app_id'];
		$obj = new Weixin($appid);
		
		$form = Db::name('formId')->alias('f')
			->join('user u', 'f.user_id = u.id', 'left')
			->where(['f.number' => 0, 'f.user_id' => $userId, 'f.create_time' => ['egt', strtotime('-7 days')]])
			->order(['f.create_time' => 'asc'])
			->field('f.id, f.form_id, u.smallapp_openid')
			->find();
		
		if(!$form) {
			return '没有模板ID;';
		}
		$templateId = $config['smallapp']['message_template']['order_tips'];
		$data = [
			'keyword1' => ['value' => '下单提醒'],
			'keyword2' => ['value' => $name],
		];
		$page = 'pages/index/index';
		$res = $obj->sendTemplate($form['smallapp_openid'], $templateId, $form['form_id'],$data, $page);
		if($res === true) {
			Db::name('formId')->where(['id' => $form['id']])->setInc('number');
			return '发送成功';
		}
		
		return '发送失败';
	}
	
	/**
	 * 发送审核通知给管理员
	 * @return string
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function sendApplyTemplate() {
		$config = config('weixin');
		$appid = $config['smallapp']['app_id'];
		$obj = new Weixin($appid);
		
		$users = Db::name('user')->alias('u')
			->join('formId f', 'u.id = f.user_id and f.number = 0 and f.create_time >= '.strtotime('-7 days'), 'left')
			->where(['u.level' => \app\admin\model\User::LEVEL_HEADQUARTERS])
			->field('f.id, f.form_id, u.smallapp_openid')
			->group('f.user_id')
			->select();
		
		if(!$users) {
			return '没有模板ID;';
		}
		$templateId = $config['smallapp']['message_template']['apply_tips'];
		$data = [
			'keyword1' => ['value' => date('Y-m-d H:i:s')],
			'keyword2' => ['value' => '有新代理入驻，请及时审核'],
		];
		$page = 'pages/index/index';
		foreach ($users as $user) {
			if($user['form_id']) {
				$res = $obj->sendTemplate($user['smallapp_openid'], $templateId, $user['form_id'],$data, $page);
				if($res === true) {
					Db::name('formId')->where(['id' => $user['id']])->setInc('number');
					
				}
			}
		}
		
		return '发送成功';
	}
	
	public function getSonIds($userId, $level) {
		$userModel = new \app\admin\model\User();
		$where['recommend_user_id'] = $userId;
		
		$shop = $this->where(['user_id' => $userId])->find();
		switch ($level) {
			case $userModel::LEVEL_THEATER:
				$agentWhere['theater_id'] = $shop['id'];
				break;
			case $userModel::LEVEL_CENTER:
				$agentWhere['center_id'] = $shop['id'];
				break;
			case $userModel::LEVEL_WAREHOUSE:
				$agentWhere['warehouse_id'] = $shop['id'];
			case $userModel::LEVEL_SHOP:
				$agentWhere['id'] = $shop['id'];
			default:;
				$agentWhere['recommend_user_id'] = $userId;
		}
		
		//推荐人是下级或自己
		$agents = Db::name('agentShop')
			->where($where)
			->whereOr($agentWhere)
			->column('user_id', 'id');
		
		$agentId = array_merge([$shop['id']], array_keys($agents));
		$promotions = Db::name('promotion')
			->where(['recommend_user_id' => $userId])
			->whereOr(['agent_shop_id' => ['in', $agentId]])
			->column('user_id', 'id');
		
		$ids = array_unique(array_merge($promotions, $agents, [$userId]));
		return $ids;
	}
}
